"use strict";

import { BdTieBa } from "@/component/BdTieBa";
import { SITES } from "@/component/Common/commonData";
import IconFont from "@/component/Common/IconFont";
import { DCDi } from "@/component/DCDi";
import { Dy } from "@/component/Dy";
import FXBaoGao from "@/component/FXBaoGao";
import { ITHome } from "@/component/ITHome";
import { PPXinWen } from "@/component/PPXinWen";
import { SSPai } from "@/component/SSPai";
import { ThirtySixKr } from "@/component/ThirtysixKr";
import { TxNews } from "@/component/TxNews";
import { WeiBo } from "@/component/WeiBo";
import { XFZuo } from "@/component/XFZuo";
import { ZhiHu } from "@/component/ZhiHu";
import { useUser } from "@/hook/useUser/useUser";
import { PAGE_SITES } from "./pageConfig";
import { dongchedi, douyin, fxbaogao, ithome, kr36, qqnews, sspai, thepaper, tieba, weibo, xfz, zhihu } from "@/servers/crawler";
import xfZuoIcon from "@/assets/xfZuo.svg";
import store from "@/store";

const ALL_SITES = [
  {
    key: SITES.txXinWen,
    label: "腾讯新闻",
    icon: (
      <IconFont
        icon={"#icon-tengxunxinwen"}
        className={"icon-tengxunxinwen"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.zh,
    label: "知乎",
    icon: (
      <IconFont
        icon={"#icon-zhihu"}
        className={"icon-zhihu"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.dy,
    label: "抖音",
    icon: (
      <IconFont
        icon={"#icon-douyin"}
        className={"icon-douyin"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.xlWeiBo,
    label: "新浪微博",
    icon: (
      <IconFont
        icon={"#icon-xinlangweibo"}
        className={"icon-xinlangweibo"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.ppXinWen,
    label: "澎湃新闻",
    icon: (
      <IconFont
        icon={"#icon-a_pengpaixinwen"}
        className={"icon-a_pengpaixinwen"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.bdTieBa,
    label: "百度贴吧",
    icon: (
      <IconFont
        icon={"#icon-baidutieba"}
        className={"icon-baidutieba"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.ssPai,
    label: "少数派",
    icon: (
      <IconFont
        icon={"#icon-sspai"}
        className={"icon-sspai"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES["36kr"],
    label: "36氪",
    icon: (
      <IconFont
        icon={"#icon-a-36kr"}
        className={"icon-a-36kr"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.itZhiJia,
    label: "IT之家",
    icon: (
      <IconFont
        icon={"#icon-itzhijia-copy-copy"}
        className={"icon-itzhijia-copy-copy"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.fxBaoGao,
    label: "发现报告",
    icon: (
      <IconFont
        icon={"#icon-weibiaoti-1-05"}
        className={"icon-weibiaoti-1-05"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
  {
    key: SITES.xfZuo,
    label: "小饭桌",
    icon: (
      <img
        style={{
          width: "1.5rem",
          height: "1.5rem",
          paddingTop: "0.4rem",
          marginRight: "-0.8rem",
          overflow: "visible",
          translate: "-0.15rem 0.25rem",
        }}
        src={xfZuoIcon}
        alt="小饭桌"
      />
    ),
  },
  {
    key: SITES.dcDi,
    label: "懂车帝",
    icon: (
      <IconFont
        icon={"#icon-dongchedi"}
        className={"icon-dongchedi"}
        width={"1.5rem"}
        height={"1.5rem"}
        viewBox={"-20 -25 100 100"}
      />
    ),
  },
];

/**
 * 根据tab获得对应的component
 * @param {String} tab
 * @param {String} hotRankings - 对应初始数据
 * @returns {JSX.Element} - 返回对应的组件
 */
export const getComponentByTab = (tab, initData) => {
  switch (tab) {
    case SITES.xlWeiBo:
      return <WeiBo initData={initData} />;
    case SITES.zh:
      return <ZhiHu initData={initData} />;
    case SITES.itZhiJia:
      return <ITHome initData={initData} />;
    case SITES.txXinWen:
      return <TxNews initData={initData} />;
    case SITES.bdTieBa:
      return <BdTieBa initData={initData} />;
    case SITES.dy:
      return <Dy initData={initData} />;
    case SITES.ssPai:
      return <SSPai initData={initData} />;
    case SITES.ppXinWen:
      return <PPXinWen initData={initData} />;
    case SITES["36kr"]:
      return <ThirtySixKr initData={initData} />;
    case SITES.fxBaoGao:
      return <FXBaoGao initHotRankings={initData?.initHotData?.items} />;
    case SITES.dcDi:
      return <DCDi initHotRankings={initData?.initHotData?.items} />;
    case SITES.xfZuo:
      return <XFZuo initData={initData} />;
    default:
      return <TxNews initData={initData} />;
  }
};

const PAGE_SIZE = 10;

/**
 * 根据tab获得对应的component,的初始列表数据
 * @param {String} tab
 * @returns {Array} - 返回对应的列表数据
 */
export const getInitHotDataByTab = async (tab) => {
  switch (tab) {
    case SITES.xlWeiBo:
      return {
        initHotData: { items: await weibo.getHot() },
        hotRankingsTop: await weibo.getTop(),
      };
    case SITES.zh:
      return {
        initHotData: await zhihu.getHotPage(1, PAGE_SIZE),
      };
    case SITES.itZhiJia:
      return {
        initHotData: await ithome.getLatestPage(1, PAGE_SIZE),
      };
    case SITES.txXinWen:
      return {
        initHotData: await qqnews.getHotPage(1, PAGE_SIZE),
        hotRankingsTop: await qqnews.getTop(),
      };
    case SITES.bdTieBa:
      return {
        initHotData: await tieba.getHotPage(1, PAGE_SIZE),
      };
    case SITES.dy:
      return {
        initHotData: await douyin.getHotPage(1, PAGE_SIZE),
      };
    case SITES.ssPai:
      return {
        initHotData: await sspai.getRecommendPage(1, PAGE_SIZE),
      };
    case SITES.ppXinWen:
      return {
        initHotData: await thepaper.getHotPage(1, PAGE_SIZE),
      };
    case SITES["36kr"]:
      return {
        initHotData: await kr36.getFlashPage(1, PAGE_SIZE),
      };
    case SITES.fxBaoGao:
      return { initHotData: { items: await fxbaogao.getDaily() } };
    case SITES.dcDi:
      return {
        initHotData: { items: await dongchedi.getHot() },
      };
    case SITES.xfZuo:
      return {
        initHotData: await xfz.getHotPage(1, PAGE_SIZE),
      };
    default:
      return {
        initHotData: await qqnews.getHotPage(1, PAGE_SIZE),
        hotRankingsTop: await qqnews.getTop(),
      };
  }
};

/**
 * 根据isImageEnable选择是否展示icon
 */
function getItems() {
  const { listDisplay } = useUser();

  return ALL_SITES.map((item) => {
    const cloned = { ...item };

    // 根据条件过滤属性
    return listDisplay === 0 ? cloned : (({ icon, ...rest }) => rest)(cloned);
  });
}

/**
 * 获取过滤后的items
 * @param {String} pageType - 页面类型
 */
export function getFilteredItems(pageType) {
  const allItems = getItems();
  const { subscribes } = useUser();
  if (pageType === "subscribe") {
    const filteredItems = allItems.filter((item) => subscribes.includes(item.key));
    return filteredItems.sort((a, b) => {
      const indexA = subscribes.indexOf(a.key);
      const indexB = subscribes.indexOf(b.key);
      return indexA - indexB;
    })
  }
  const allowedSites = PAGE_SITES[pageType] || [];
  return allItems.filter((item) => allowedSites.includes(item.key));
}


// 通用加载器
export function pageLoader(pageType) {
  return async function loader({ request }) {
    const url = new URL(request.url);
    const state = store.getState();
    const subscribes = state.user.subscribes;
    let allowedSites;
    // 根据页面类型设置允许的站点
    if (pageType === "subscribe") {
      allowedSites = subscribes || [];
    } else {
      allowedSites = PAGE_SITES[pageType] || [];
    }
    
    let tab = url.searchParams.get("tab");
    if (!tab || !allowedSites.includes(tab)) {
      tab = allowedSites[0] || "txXinWen";
    }
    
    let initData;
    try {
      initData = await getInitHotDataByTab(tab);
    } catch (e) {
      initData = {
        initHotData: {},
        hotRankingsTop: [],
      };
    }

    return { tab, initData };
  };
}
